package com.example.hasee.zhcd.Activities.ChuanWu;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hasee.zhcd.Adapters.OutBusinessAdapter;
import com.example.hasee.zhcd.Base.BaseActivity;
import com.example.hasee.zhcd.Bean.EventMsg;
import com.example.hasee.zhcd.R;
import com.example.hasee.zhcd.Util.DateTimePickDialogUtil;
import com.example.hasee.zhcd.Util.GlobalParameter;
import com.example.hasee.zhcd.Util.ProgressDialogUtils;
import com.example.hasee.zhcd.View.NoScrollListView;
import com.example.hasee.zhcd.View.PullToRefreshView;
import com.baoyz.swipemenulistview.*;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class OutBusinessActivity extends BaseActivity implements PullToRefreshView.OnFooterRefreshListener, PullToRefreshView.OnHeaderRefreshListener {
    private HashMap<String, String> loginmap = (HashMap<String, String>) GlobalParameter.get("loginmap");
    private TextView title;
    private ImageView back;
    private ImageView home;
    private TextView message;
    private EditText start_date;
    private EditText end_date;
    private CheckBox check_box;
    private Button btn_query;
    private PullToRefreshView mPullToRefreshView;
    private NoScrollListView out_business_list;
    private ScrollView scrollView;
    private String startString;
    private String endString;
    private String strMe = "0";
    private int pagenum = 1;
    private String strFid;
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private List<HashMap<String, String>> newlist = new ArrayList<HashMap<String, String>>();
    private OutBusinessAdapter adapter;

    @Override
    public int contentViewId() {
        return R.layout.activity_out_business;
    }

    @Override
    public void set() {
        title.setText("外勤管理");
        back.setOnClickListener(this);
        home.setImageResource(R.mipmap.add);
        home.setOnClickListener(this);
        start_date.setOnClickListener(this);
        end_date.setOnClickListener(this);
        check_box.setChecked(false);
        String OldDate = getTime().substring(0, 8) + "01";
        start_date.setText(OldDate);
        end_date.setText(getTime());
        startString = start_date.getText().toString();
        endString = end_date.getText().toString();
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
        mPullToRefreshView.setLastUpdated(new Date().toLocaleString());
        check_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                pagenum = 1;
                if (b) {
                    strMe = "1";
                } else {
                    strMe = "0";
                }
                getOBList();
            }
        });
        getOBList();

    }

    @Override
    public void init() {
//        Log.e("user", loginmap.get("user"));
        back = (ImageView) findViewById(R.id.back);
        home = (ImageView) findViewById(R.id.home);
        title = (TextView) findViewById(R.id.centertitle);
        message = (TextView) findViewById(R.id.message);
        check_box = (CheckBox) findViewById(R.id.check_box);
        btn_query = (Button) findViewById(R.id.btn_query);
        start_date = (EditText) findViewById(R.id.start_date);
        end_date = (EditText) findViewById(R.id.end_date);
        out_business_list = (NoScrollListView) findViewById(R.id.out_list);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
    }

    private void getOBList() {
        ProgressDialogUtils.createProgressDialog(OutBusinessActivity.this, "正在获取列表...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strKSSJ", startString);
        map.put("strJSSJ", endString);
        map.put("strUser", loginmap.get("user"));
        map.put("strPageNum", pagenum + "");
        map.put("strMe", strMe);
        httpUtils.get("ZHCW_wqList", map, "ZHCW_wqList");
    }

    private void getDel() {
        ProgressDialogUtils.createProgressDialog(OutBusinessActivity.this, "正在删除...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strFID", strFid);
        httpUtils.get("ZHCW_WQDel", map, "ZHCW_WQDel");
    }

    @Override
    public void getEventData(EventMsg msg) {
        switch (msg.getAction()) {
            case "Fail":
                ProgressDialogUtils.closeProgressDialog();
                Toast.makeText(OutBusinessActivity.this, "操作失败，请检查网络！", Toast.LENGTH_LONG).show();
                break;
            case "ZHCW_wqList":
                //{"fid":"32150", "fberth":"904", "fshipname":"广茂", "fhc":"1808", "fdlsj":"06-05 18:20", "fdly":"陈义军",
                // "fdlmd":"其他事项", "ftznr":"其他事项:换运单,", "fsyn":"QHD201802254", "fbz":""}
                ProgressDialogUtils.closeProgressDialog();
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    String rspmessage = json.getString("rspmessage");
                    if ("0".equals(rspcode)) {
                        out_business_list.setVisibility(View.VISIBLE);
                        if ("".equals(rspmessage)) {
                            message.setVisibility(View.GONE);
                        } else {
                            message.setVisibility(View.VISIBLE);
                            message.setText(rspmessage);
                        }


                        JSONArray data = json.getJSONArray("data");
                        if (pagenum == 1) {
                            pagenum = pagenum + 1;
                            list.clear();
                            for (int i = 0; i < data.length(); i++) {
                                HashMap<String, String> lmap = new HashMap<String, String>();
                                lmap.put("fid", data.getJSONObject(i).getString("fid"));
                                lmap.put("fberth", data.getJSONObject(i).getString("fberth"));
                                lmap.put("fshipname", data.getJSONObject(i).getString("fshipname"));
                                lmap.put("fhc", data.getJSONObject(i).getString("fhc"));
                                lmap.put("fdlsj", data.getJSONObject(i).getString("fdlsj"));
                                lmap.put("fdly", data.getJSONObject(i).getString("fdly"));
                                lmap.put("fdlmd", data.getJSONObject(i).getString("fdlmd"));
                                lmap.put("ftznr", data.getJSONObject(i).getString("ftznr"));
                                lmap.put("fsyn", data.getJSONObject(i).getString("fsyn"));
                                lmap.put("fbz", data.getJSONObject(i).getString("fbz"));
                                lmap.put("fshipcode", data.getJSONObject(i).getString("fshipcode"));
                                lmap.put("fxx", data.getJSONObject(i).getString("fxx"));
                                lmap.put("fdly", data.getJSONObject(i).getString("fdly"));
                                list.add(lmap);
                            }
                            adapter = new OutBusinessAdapter(OutBusinessActivity.this, list);
                            out_business_list.setAdapter(adapter);
                            out_business_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                                @Override
                                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    strFid = list.get(i).get("fid");
                                    DeleteDialog("是否删除 " + list.get(i).get("fshipname") + " 的外勤?");
                                    return false;
                                }
                            });
                        } else {
                            pagenum = pagenum + 1;
                            if (data.length() == 0) {

                                Toast.makeText(getApplicationContext(), "无更多新消息！",
                                        Toast.LENGTH_LONG).show();
                                mPullToRefreshView.onFooterRefreshComplete();
                            } else {
                                newlist.clear();
                                for (int i = 0; i < data.length(); i++) {
                                    HashMap<String, String> lmap = new HashMap<String, String>();
                                    lmap.put("fid", data.getJSONObject(i).getString("fid"));
                                    lmap.put("fberth", data.getJSONObject(i).getString("fberth"));
                                    lmap.put("fshipname", data.getJSONObject(i).getString("fshipname"));
                                    lmap.put("fhc", data.getJSONObject(i).getString("fhc"));
                                    lmap.put("fdlsj", data.getJSONObject(i).getString("fdlsj"));
                                    lmap.put("fdly", data.getJSONObject(i).getString("fdly"));
                                    lmap.put("fdlmd", data.getJSONObject(i).getString("fdlmd"));
                                    lmap.put("ftznr", data.getJSONObject(i).getString("ftznr"));
                                    lmap.put("fsyn", data.getJSONObject(i).getString("fsyn"));
                                    lmap.put("fbz", data.getJSONObject(i).getString("fbz"));
                                    lmap.put("fshipcode", data.getJSONObject(i).getString("fshipcode"));
                                    lmap.put("fxx", data.getJSONObject(i).getString("fxx"));
                                    newlist.add(lmap);
                                }
                                for (int j = 0; j < newlist.size(); j++) {
                                    list.add(newlist.get(j));
                                    adapter.notifyDataSetChanged();
                                }

                            }
                        }
                        mPullToRefreshView.onHeaderRefreshComplete();
                        mPullToRefreshView.onFooterRefreshComplete();
                    } else {
                        if (pagenum == 1) {
                            out_business_list.setVisibility(View.GONE);
                        }
                        Toast.makeText(getApplicationContext(), "无更多新消息！",
                                Toast.LENGTH_LONG).show();
                        mPullToRefreshView.onFooterRefreshComplete();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "ZHCW_WQDel":
                ProgressDialogUtils.closeProgressDialog();
//                Log.e("ZHCW_WQDel", msg.getMsg());
                //ZHCW_WQDel: {"data":"","rspcode": 0,"rspmessage":"删除成功"}
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    String rspmessage = json.getString("rspmessage");
                    if ("0".equals(rspcode)) {
                        DelSucsessDialog(rspmessage);
                    } else {
                        Toast.makeText(getApplicationContext(), rspmessage,
                                Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.home:
                Intent intent = new Intent(OutBusinessActivity.this, OBInputActivity.class);
                intent.putExtra("fsyn", "0");
                intent.putExtra("fid", "0");
                intent.putExtra("fshipname", "0");
                intent.putExtra("fshipcode", "0");
                intent.putExtra("ftznr", "0");
                intent.putExtra("fbz", "0");
                intent.putExtra("add", true);
                startActivity(intent);
                break;
            case R.id.start_date:
                String t1 = "";
                if (start_date.getText().toString().equals("")) {
                    t1 = getTime();
                } else {
                    t1 = start_date.getText().toString();
                }
                DateTimePickDialogUtil dialog1 = new DateTimePickDialogUtil(this,
                        t1);
                dialog1.dateTimePicKDialog(start_date);
                break;
            case R.id.end_date:
                String t2 = "";
                if (end_date.getText().toString().equals("")) {
                    t2 = getTime();
                } else {
                    t2 = end_date.getText().toString();
                }
                DateTimePickDialogUtil dialog2 = new DateTimePickDialogUtil(this,
                        t2);
                dialog2.dateTimePicKDialog(end_date);
                break;
            case R.id.btn_query:
                pagenum = 1;
                list.clear();
                startString = start_date.getText().toString();
                endString = end_date.getText().toString();
                View errorview = inputCheck();
                if (errorview != null) {
                    errorview.setFocusable(true);
                    errorview.requestFocus();
                    errorview.setFocusableInTouchMode(true);
                    return;
                } else {
                    getOBList();
                }
                break;
        }
    }

    public String getTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        return df.format(new Date());// new Date()为获取当前系统时间
    }

    public static String getOldDate(int distanceDay) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        date.set(Calendar.DATE, date.get(Calendar.DATE) + distanceDay);
        Date endDate = null;
        try {
            endDate = dft.parse(dft.format(date.getTime()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dft.format(endDate);
    }

    private View inputCheck() {
        if (startString.length() == 0) {
            return start_date;
        } else if (endString.length() == 0) {
            return end_date;
        }
        return null;
    }

    private void DeleteDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OutBusinessActivity.this);
        builder.setMessage(message);
        builder.setTitle("提示");
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
                Log.e("strFid", strFid);
                getDel();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void DelSucsessDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OutBusinessActivity.this);
        builder.setMessage(message);
        builder.setTitle("提示");
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                arg0.dismiss();
                pagenum = 1;
                list.clear();
                getOBList();
            }
        });
        builder.create().setCanceledOnTouchOutside(false);
        builder.setCancelable(false);
        builder.show();
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        getOBList();
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pagenum = 1;
        getOBList();
    }
}
